package one;
//装饰者模式

//组件接口
interface Beverage {
 String getDescription();
 double cost();
}

//具体组件类 Coffee
class Coffee implements Beverage {
 @Override
 public String getDescription() {
     return "Coffee";
 }

 @Override
 public double cost() {
     return 1.99;
 }
}

//装饰者抽象类 CondimentDecorator
abstract class CondimentDecorator implements Beverage {
 protected Beverage beverage;

 public CondimentDecorator(Beverage beverage) {
     this.beverage = beverage;
 }

 @Override
 public abstract String getDescription();
}

//具体装饰者类 Milk
class Milk extends CondimentDecorator {
 public Milk(Beverage beverage) {
     super(beverage);
 }

 @Override
 public String getDescription() {
     return beverage.getDescription() + ", Milk";
 }

 @Override
 public double cost() {
     return beverage.cost() + 0.20;
 }
}

//具体装饰者类 Sugar
class Sugar extends CondimentDecorator {
 public Sugar(Beverage beverage) {
     super(beverage);
 }

 @Override
 public String getDescription() {
     return beverage.getDescription() + ", Sugar";
 }

 @Override
 public double cost() {
     return beverage.cost() + 0.15;
 }
}

//测试装饰者模式
public class DecoratorPatternDemo {
 public static void main(String[] args) {
     Beverage coffee = new Coffee();
     System.out.println(coffee.getDescription() + " $" + coffee.cost()); // 输出 "Coffee $1.99"

     Beverage milkCoffee = new Milk(coffee);
     System.out.println(milkCoffee.getDescription() + " $" + milkCoffee.cost()); // 输出 "Coffee, Milk $2.19"

     Beverage sugarMilkCoffee = new Sugar(milkCoffee);
     System.out.println(sugarMilkCoffee.getDescription() + " $" + sugarMilkCoffee.cost()); // 输出 "Coffee, Milk, Sugar $2.34"
 }
}



